<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i>
                    {{pageTitle}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container" :style="{'min-height': containerHeight + 'px'}">
            <div class="handle-box flex flex-center">
                <el-button type="primary" icon="el-icon-folder" @click="submitForm('ruleForm')">保存</el-button>
            </div>
            <div class="table-form-box">
                <el-form
                    :model="formData"
                    :rules="rules"
                    ref="ruleForm"
                    label-width="100px"
                    class="demo-ruleForm"
                >
                    <el-form-item label="账户名" prop="account">
                        <el-input
                            v-model="formData.account"
                            autocomplete="off"
                            clearable
                            :disabled="editStatus"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input
                            type="password"
                            v-model="formData.password"
                            autocomplete="off"
                            clearable
                            :disabled="editStatus"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="姓名" prop="name">
                        <el-input
                            v-model="formData.name"
                            autocomplete="off"
                            clearable
                            :disabled="editStatus"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="锁定账号" prop="isLock">
                        <el-switch v-model="formData.isLock" :active-value="2" :inactive-value="1"></el-switch>
                    </el-form-item>

                    <el-form-item label="备注" prop="remark">
                        <el-input
                            v-model="formData.remark"
                            type="textarea"
                            maxlength="300"
                            show-word-limit
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="签名图片" prop="signature">
                        <el-image :src="formData.signature">
                            <div slot="error" class="image-slot">
                                <i class="el-icon-picture-outline"></i>
                            </div>
                        </el-image>

                        <div>
                            <input
                                type="file"
                                ncropImgame="image"
                                accept="image/*"
                                @change="setImage"
                            />
                            <span>最佳大小:180*60 像素</span>
                        </div>
                    </el-form-item>

                    <el-form-item label="人事档案" prop="employeeStatus" v-if="!isEdit">
                        <el-radio-group v-model="formData.employeeStatus">
                            <el-radio :label="1">新增档案</el-radio>
                            <el-radio :label="0">关联已有档案</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item
                        label="关联已有档案"
                        prop="employeeId"
                        v-if="formData.employeeStatus == 0"
                        v-show="!isEdit"
                    >
                        <div @click="showTreeDialog02('在职人员关联')">
                            <el-input v-model="formData.employeeId" readonly>
                                <i slot="suffix" class="el-icon-search"></i>
                            </el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="部门" prop="organizationName">
                        <el-input v-model="formData.organizationName" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="岗位" prop="jobName">
                        <div @click="showTreeDialog01('岗位')">
                            <el-input v-model="formData.jobName" readonly>
                                <i slot="suffix" class="el-icon-search"></i>
                            </el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="上级" prop="higherUpName">
                        <div @click="showTreeDialog('上级')">
                            <el-input v-model="formData.higherUpName" readonly>
                                <i slot="suffix" class="el-icon-search"></i>
                            </el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="角色">
                        <el-tag
                            :key="tag"
                            v-for="tag in dynamicTags"
                            :disable-transitions="false"
                        >{{tag}}</el-tag>
                        <el-button class="button-new-tag" size="small" @click="addRoles">+添加角色</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <!-- 选择上级 -->
        <tree-search
            :isShow="showSearch"
            :dialogTitle="searchDialogTit"
            @edit="searchBack"
            @close="closeTreeDialog"
        ></tree-search>

        <!-- 选择部门岗位 -->
        <tree-search-job
            :isShow="showSearch01"
            :dialogTitle="searchDialogTit01"
            @edit="searchBack01"
            @close="closeTreeDialog01"
        ></tree-search-job>

        <!-- 在职人员关联 -->
        <el-dialog title="在职人员关联" :visible.sync="showSearch02" fullscreen>
            <div class="tree-box flex">
                <div class="flex-left">
                    <el-tree
                        :data="treeData"
                        :props="defaultProps"
                        @node-click="handleNodeClick"
                        default-expand-all
                    ></el-tree>
                </div>
                <div class="flex-right">
                    <!-- 表格 -->
                    <table-List
                        ref="tableList"
                        :tableData="tableData"
                        :tableHeader="tableHeader"
                        :loading="loading"
                        :pagination="pagination"
                        @pageChange="pageChange"
                        @selectFun="selectFun"
                        @sortChange="sortChange"
                    ></table-List>
                </div>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="showSearch02 = false">取 消</el-button>
                <el-button type="primary" @click="saveEmployeeId">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 角色选择 -->
        <el-dialog title="角色选择" :visible.sync="showSearch03" width="50%">
            <div>
                <el-transfer
                    v-model="roles"
                    :data="roleData"
                    :titles="['待选角色', '已选角色']"
                    :button-texts="['从已选移除', '从待选添加']"
                    :props="{ key: 'id', label: 'roleName' }"
                ></el-transfer>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showSearch03 = false">取 消</el-button>
                <el-button type="primary" @click="saveRole">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import appMain from '../../../utils/app_main';
import { fileUploadImage } from '../../../api/index';
import config from '../../../utils/config';
export default {
    name: 'transfer',
    data() {
        return {
            pageTitle: '',
            containerHeight: '',
            formData: {
                account: '', //用户名-账号
                higherUpAccount: '', //上级领导账号
                higherUpId: '', //上级领导ID
                higherUpName: '', //上级领导名字
                isLock: 0, //是否锁定，1 否  2锁定
                jobId: '', //岗位ID
                jobName: '', //岗位名字
                name: '', //姓名
                organizationId: '', //组织ID
                organizationName: '', //组织名
                password: '', //
                remark: '', //
                roles: [], //角色id
                signature: '', //签名照片
                employeeId: '', //关联档案id
                employeeStatus: 1 //人事档案:1新增档案
            },
            rules: {
                account: [
                    {
                        required: true,
                        message: '请输入',
                        trigger: 'change'
                    },
                    {
                        min: 6,
                        max: 20,
                        message: '长度在 6 到 20 个字符',
                        trigger: 'change'
                    }
                ],
                password: [
                    {
                        required: true,
                        message: '请输入',
                        trigger: 'change'
                    },
                    {
                        min: 6,
                        max: 30,
                        message: '长度在 6 到 30 个字符',
                        trigger: 'change'
                    },
                    {
                        required: true,
                        pattern: /^(?=.*[0-9])(?=.*[a-zA-Z]).{6,30}$/,
                        message: '您的密码复杂度太低（密码中必须包含字母、数字），请及时修改密码！',
                        trigger: 'change'
                    }
                ],
                name: [
                    {
                        required: true,
                        message: '请输入姓名',
                        trigger: 'change'
                    },
                    {
                        min: 2,
                        max: 18,
                        message: '长度在 2 到 18 个字符',
                        trigger: 'change'
                    },
                    {
                        required: true,
                        pattern: /^[\u4E00-\u9FA5A-Za-z\s]+(·[\u4E00-\u9FA5A-Za-z]+)*$/,
                        message: '请输入格式正确的姓名',
                        trigger: 'change'
                    }
                ],
                organizationName: [
                    {
                        required: true,
                        message: '请选择',
                        trigger: 'change'
                    }
                ],
                jobName: [
                    {
                        required: true,
                        message: '请选择',
                        trigger: 'change'
                    }
                ],
                higherUpName: [
                    {
                        required: true,
                        message: '请选择',
                        trigger: 'change'
                    }
                ],

                remarks: [
                    {
                        min: 0,
                        max: 3000,
                        message: '长度在 0 到 300 个字符',
                        trigger: 'change'
                    }
                ]
            },
            dynamicTags: [],
            isEdit: false,
            editId: '',
            dialogVisible: false,
            showSearch: false, // 显示搜索树弹窗
            searchDialogTit: '编辑',
            showSearch01: false, // 显示搜索树弹窗
            searchDialogTit01: '编辑',
            showSearch02: false, // 显示搜索树弹窗
            showSearch03: false, // 显示搜索树弹窗
            loading: false,
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            tableData: [],
            treeData: [],
            multipleSelection: [],
            // 分页信息
            pagination: {
                pageIndex: 1,
                pageSize: 10,
                pageTotal: 60
            },
            tableHeader: [
                // 表头数据
                { prop: 'id', label: '人员编号', minWidth: '100px', router: 'employeeDetail', routerId: 'id', sortable: 'custom' },
                { prop: 'departName', label: '部门', minWidth: '100px', sortable: 'custom' },
                {
                    prop: 'name',
                    label: '姓名',
                    router: 'employeeDetail',
                    routerId: 'id',
                    sortable: 'custom'
                },
                { prop: 'jobNumber', label: '工号', minWidth: '100px', sortable: 'custom' },
                {
                    prop: 'gender',
                    label: '性别',
                    sortable: 'custom',
                    formatData: function(val) {
                        return val == true ? '男' : '女';
                    }
                },
                {
                    prop: 'birthday',
                    label: '生日',
                    formatData: function(val) {
                        let date = new Date(val);
                        return appMain.formatDate(date, 'yyyy-MM-dd');
                    },
                    sortable: 'custom'
                },

                { prop: 'jobRole', label: '岗位', minWidth: '100px', sortable: 'custom' },
                { prop: 'itileLevelName', label: '职称职等', minWidth: '100px', sortable: 'custom' },
                {
                    prop: 'onbordingTime',
                    label: '入职时间',
                    formatData: function(val) {
                        let date = new Date(val);
                        return appMain.formatDate(date, 'yyyy-MM-dd');
                    },
                    sortable: 'custom'
                }
            ],
            query: {
                departName: '', //部门名字
                departId: '' //部门编号
            },
            roleData: [],
            roles: [],
            editStatus: false
        };
    },
    created() {
        // 如果有id就是跳转过来修改的
        if (this.$route.query.id) {
            this.editId = this.$route.query.id;
            this.isEdit = true;
            this.editStatus = true;
            this.rules.password = [];
            this.rules.account = [];
            this.rules.name = [];
            this.getData(); // 获取要修改的数据
        } else {
            this.isEdit = false;
            this.formData = {
                account: '', //用户名-账号
                higherUpAccount: '', //上级领导账号
                higherUpId: '', //上级领导ID
                higherUpName: '', //上级领导名字
                isLock: 0, //是否锁定，1 否  2锁定
                jobId: '', //岗位ID
                jobName: '', //岗位名字
                name: '', //姓名
                organizationId: '', //组织ID
                organizationName: '', //组织名
                password: '', //
                remark: '', //
                roles: [], //角色id
                signature: '', //签名照片
                employeeId: '', //关联档案id
                employeeStatus: 1 //人事档案:1新增档案
            };
        }
    },
    methods: {
        getData() {
            appMain
                .accountFindById({}, this.editId)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.formData = res.data.data;

                        for (const key in this.formData.roles) {
                            this.roles.push(this.formData.roles[key].id);
                            this.dynamicTags.push(this.formData.roles[key].roleName);
                        }
                        //获取人员档案附件
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },

        submit() {
            let params = this.formData;
            let mothedName = '';

            if (this.formData.employeeStatus == 1) {
                this.formData.employeeId = '';
            }

            if (this.isEdit) {
                mothedName = 'accountUpdateById';
            } else {
                mothedName = 'accountInsert';
            }

            appMain[mothedName](params)
                .then(res => {
                    if (res.data.code === 20000) {
                        if (this.isEdit) {
                            this.getData();
                        }
                        this.$router.push({
                            path: '/useraccountList' //跳转的路径
                        });
                        this.$message({
                            message: res.data.message,
                            type: 'success'
                        });
                    } else {
                        this.$message({
                            message: res.data.message,
                            type: 'error'
                        });
                    }
                })
                .catch(err => {
                    console.log(err);
                });
            console.log(this.$router);
        },
        // 选择员工
        showTreeDialog(tit) {
            console.log('showTreeDialog');
            this.searchDialogTit = tit;
            this.showSearch = true;
        },

        // 树组件搜索结果返回
        searchBack(data) {
            console.log(data.backData, 'searchTreeBack');
            this.formData.higherUpName = data.backData.name;
            this.formData.higherUpAccount = data.backData.account;
            this.formData.higherUpId = data.backData.id;
            this.showSearch = false;
        },
        closeTreeDialog(data) {
            this.showSearch = data.showDialog;
        },
        // 选择岗位
        showTreeDialog01(tit) {
            console.log('showTreeDialog');
            this.searchDialogTit01 = tit;
            this.showSearch01 = true;
        },

        // 树组件搜索结果返回
        searchBack01(data) {
            console.log(data.backData, 'searchTreeJobBack');
            this.formData.jobName = data.backData.name;
            this.formData.jobId = data.backData.id;
            this.formData.organizationName = data.backData.departName;
            this.formData.organizationId = data.backData.departId;
            this.showSearch01 = false;
        },
        closeTreeDialog01(data) {
            this.showSearch01 = data.showDialog;
        },

        // 选择岗位
        showTreeDialog02() {
            this.showSearch02 = true;
            this.getData1();
            this.getTree();
        },

        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.submit();
                    //this.resetForm('ruleForm');
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        setImage(e) {
            const file = e.target.files[0];
            console.log('file', file);
            if (file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                if (isJPG && isLt2M) {
                    this.imageuploaded(file);
                }
            }
        },
        //图片上传
        imageuploaded(file) {
            fileUploadImage(file, config.url.uploadFile).then(res => {
                if (res.code === 20000) {
                    this.formData.signature = res.data;
                } else {
                    this.formData.signature = '';
                    this.$message.error('服务器繁忙，请稍后再试');
                }
            });

            this.dialogVisible = false;
        },
        handleClose(tag) {
            this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
        },
        addRoles() {
            //this.dynamicTags = [];
            this.showSearch03 = true;
            this.getRoleList();

            // this.$nextTick(_ => {
            //     //this.$refs.saveTagInput.$refs.input.focus();
            // });
        },
        //分页导航
        pageChange(data) {
            this.pagination = data.backData;
            console.log('pageChange:', this.pagination);
            //分页变化--请求接口
            this.getData1();
        },
        // 组件选择完后把数据传过来
        selectFun(data) {
            this.multipleSelection = data.backData;
        },
        //表格组件返回排序对象
        sortChange(data) {
            let column = data.backData;
            //排序
            if (column.order) {
                //倒序
                if (column.order === 'descending') {
                    this.query.sortColumn = column.prop + ' ' + 'desc';
                } else {
                    this.query.sortColumn = column.prop;
                }
            } else {
                //不排序
                this.query.sortColumn = '';
            }
            this.getData1();
        },
        //搜索
        getData1() {
            this.loading = true;
            let params = {
                pageNo: this.pagination.pageIndex,
                pageSize: this.pagination.pageSize,
                record: this.query
            };
            appMain
                .employeeFindAllPageByDTO(params)
                .then(res => {
                    if (res.data.code === 20000) {
                        //TODO 测试环境使用
                        this.timer = setTimeout(() => {
                            //设置延迟执行
                            this.loading = false;
                        }, 1000);
                        this.tableData = res.data.data.list;
                        this.pagination.pageSize = res.data.data.pageSize;
                        this.pagination.pageIndex = res.data.data.pageNum;
                        this.pagination.pageTotal = res.data.data.total;
                    } else {
                        this.loading = false;
                        this.$message.error('服务器繁忙，请稍后再试');
                    }
                })
                .catch(err => {
                    this.loading = false;
                    console.log(err);
                });
        },
        // 树元素点击事件
        handleNodeClick(e) {
            console.log(e, 'treeItem');
            // 发请求获取右下表格数据
            this.query.departId = e.id;
            this.query.departName = e.name;
            this.getData1();
        },
        // 获取树的数据
        getTree() {
            appMain
                .organizationList()
                .then(res => {
                    if (res.data.code === 20000) {
                        this.treeData = res.data.data;
                    } else {
                        this.$message.error('服务器繁忙，请稍后再试');
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        saveEmployeeId() {
            if (this.multipleSelection.length > 1) {
                this.$message('只能选择一条记录');
                return;
            }
            this.formData.employeeId = this.multipleSelection[0].id;
            this.showSearch02 = false;
        },
        getRoleList() {
            appMain
                .roleFindAllPageByDTO(this.query)
                .then(res => {
                    if (res.data.code === 20000) {
                        //TODO 测试环境使用

                        this.roleData = res.data.data;
                        console.log('getData tableData', this.tableData);
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    this.loading = false;
                    console.log(err);
                });
        },
        saveRole() {
            console.log('saveRole', this.roles);
            this.dynamicTags = [];
            this.formData.roles = [];
            for (const key1 in this.roleData) {
                for (const key in this.roles) {
                    console.log('saveRole key', this.roles[key]);
                    console.log('saveRole key1', this.roleData);
                    console.log('saveRole key1', this.roleData[key1].roleName);
                    if (this.roles[key] === this.roleData[key1].id) {
                        this.dynamicTags.push(this.roleData[key1].roleName);
                        this.formData.roles.push(this.roleData[key1]);
                    }
                }
            }
            console.log('saveRole dynamicTags', this.dynamicTags);
            this.showSearch03 = false;
        }
    },
    mounted() {
        var div_height = window.screen.availHeight;
        var height = div_height - 100;
        this.containerHeight = height - 160;
        this.pageTitle = this.$router.currentRoute.meta.title;
        // console.log(this.$router, 'router')
    }
};
</script>

<style scoped>
.container {
    padding-bottom: 50px;
}
.handle-box {
    /* padding: 5px 50px; */
    width: 100%;
    background-color: #fff;
    position: absolute;
    left: 0;
    bottom: 0px;
    border-bottom: 1px solid #ddd;
    border-top: 1px solid #ddd;
    z-index: 1;
}

.el-image {
    height: 60px;
    width: 180px;
    border: 1px solid #000;
}

.el-tag + .el-tag {
    margin-left: 10px;
}
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}

.tree-box {
    border: 1px solid #ddd;
    margin-top: 20px;
    height: calc(100% - 146px);
}
.tree-box .flex-left {
    width: 200px;
    border-right: 1px solid #ddd;
}
.tree-box .flex-right {
    width: calc(100% - 200px);
}
.el-input {
    max-width: 600px;
}
.el-textarea {
    max-width: 600px;
}
</style>
